#!/bin/bash
#
# A script to start/stop the CoreNLP server on port 80, made
# in particular for the configuration running at corenlp.run.
# This script should be placed into:
#
#   /etc/init.d/corenlp
#
# To run it at startup, link to the script using:
#
#   ln -s /etc/init.d/conenlp /etc/rc.2/S75corenlp
#
# Usage:
#
#    service corenlp [start|stop]
#    ./corenlp [start|stop]
# 

#
# Set this to the username you would like to use to run the server.
# Make sure that this user can authbind to port 80!
#
SERVER_USER="nlp"
CORENLP_DIR="/opt/corenlp"


do_start()
{
  if [ -e "$CORENLP_DIR/corenlp.shutdown" ]; then
    echo "CoreNLP server is already running!"
    echo "If you are sure this is a mistake, delete the file:"
    echo "$CORENLP_DIR/corenlp.shutdown"
  else
    export CLASSPATH=""
    for JAR in `find "$CORENLP_DIR" -name "*.jar"`; do
      CLASSPATH="$CLASSPATH:$JAR"
    done
    nohup su nlp -c "/usr/local/bin/authbind --deep java -Djava.net.preferIPv4Stack=true -Djava.io.tmpdir=/opt/corenlp -cp "$CLASSPATH" -XX:+UseG1GC -XX:MaxGCPauseMillis=500 -XX:+UseStringDeduplication -XX:SoftRefLRUPolicyMSPerMB=100 -mx20g edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 80" \
      > "$CORENLP_DIR/stdout.log" 2> "$CORENLP_DIR/stderr.log" &
    echo "CoreNLP server started."
  fi  
}

do_stop() 
{
  if [ ! -e "$CORENLP_DIR/corenlp.shutdown" ]; then
    echo "CoreNLP server is not running"
  else
    KEY=`cat "$CORENLP_DIR/corenlp.shutdown"`
    curl "localhost/shutdown?key=$KEY"
    echo "CoreNLP server stopped"
  fi
}

do_restart()
{
  do_stop
  sleep 3
  do_start
}

case $1 in
start) do_start
;;
stop) do_stop
;;
restart) do_restart
;;
esac

